﻿using System;
using System.Linq;
using System.IO;
using Wala.Connection.Exceptions;

namespace Wala.Connection.ComConnections
{
   public class CoreMessage
    {

	public int size;
	public int type;
	public long id;
	public bool streaming;
    public byte[] content;

	public CoreMessage(){}
	
	public CoreMessage(MemoryStream data) {
		int magic1 = data.ReadByte();
		int magic2 = data.ReadByte();
		if(magic1 == -1 || magic2 == -1) 
			throw new SocketClosedException("Socket is close");
		
		if (magic1 !=  0xEE || magic2 != 0xEE)
			throw new MagicByteNotMatchException("Magic bytes not match");
		size = (data.ReadByte() & 0xFF);
		size <<= 8;
		size += (data.ReadByte() & 0xFF);
		type = (data.ReadByte() & 0xFF);
		type = (type << 8) + (data.ReadByte() & 0xFF);
		type = (type << 8) + (data.ReadByte() & 0xFF);
		int tmp = data.ReadByte();
		if ((tmp & 0x01) == 0x01)
			streaming = true;
		else
			streaming = false;

		if ((tmp & 0x02) == 0x02) {
			id = 0;
			for (int i = 0; i < 8; i++) {
				id <<= 8;
				id += (data.ReadByte() & 0xFF);
			}

            if (size < 16) throw new WrongPacketFormatException("Wrong packet format");

            content = new byte[size - 16];
            int r = data.Read(content,0,content.Count());
            if (r < 0)
            {
                throw new SocketClosedException("Socket is close");
            }
            while (r < content.Count())
            {
                try
                {
                    r += data.Read(content, r, content.Count() - r);
                }
                catch (Exception ex)
                {
                    throw new WrongPacketFormatException("Wrong packet format");
                }             
            }

            if (r != content.Count()) throw new WrongPacketFormatException("Wrong packet format");
			
		} else {
			id = 0;
            if (size < 8) throw new WrongPacketFormatException("Wrong packet format");
            content = new byte[size - 8];
            int r = data.Read(content, 0, content.Count());
            if (r < 0)
            {
                throw new SocketClosedException("Socket is close");
            }
            while (r < content.Count())
            {
                try
                {
                    r += data.Read(content, r, content.Count() - r);
                }
                catch (System.Exception ex)
                {
                    throw new WrongPacketFormatException("Wrong packet format");
                }        
            }
            if (r != content.Count()) throw new WrongPacketFormatException("Wrong packet format");
		}

        //using (var stream = new MemoryStream(content))
        //{
        //    msg = Serializer.Deserialize<LoginMsg>(stream);
        //}
	}
    }
}
